package com.inspectortime.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContextException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

/**
 * Works like MultiActionController except it will default to using method name
 * as view name if handler method is not found
 * 
 * @author mkvalsvik
 * 
 */
public class MethodNameDefaultingMultiActionController extends
		MultiActionController {

	private String actionableExtension = ".html";

	private Log log = LogFactory
			.getLog(MethodNameDefaultingMultiActionController.class);

	public MethodNameDefaultingMultiActionController()
			throws ApplicationContextException {
		super();
	}

	public MethodNameDefaultingMultiActionController(Object delegate)
			throws ApplicationContextException {
		super(delegate);
	}

	/**
	 * Takes a request path, sees if there's a handler method in this class,
	 * defaults to rendering a view with the same name as the path if not
	 */
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String methodName = null;
		try {
			methodName = this.getMethodNameResolver().getHandlerMethodName(
					request);
			return invokeNamedMethod(methodName, request, response);
		} catch (NoSuchRequestHandlingMethodException ex) {
			String servletPath = request.getServletPath();
			if (servletPath.equals("/" + methodName + actionableExtension)) {
				log.debug("Resolved path " + servletPath + " to view "
						+ methodName);
				ModelAndView mv = new ModelAndView(methodName);
				return mv;
			} else {

				// Strip the leading slash and trailing ".xxx" to get view name
				String viewName = servletPath.substring(1, servletPath.length()
						- (actionableExtension.length()));
				log.debug("Resolved path " + servletPath + " to view "
						+ viewName);
				ModelAndView mv = new ModelAndView(viewName);
				return mv;
			}
		}
	}

	public void setActionableExtension(String actionableExtension) {
		this.actionableExtension = actionableExtension;
	}

}
